import 'package:icooker/converts/json/entry_factory.dart';

/// 解析基类
/// http://events.jianshu.io/p/3c50812865d1
class BaseBeanEntry<T> {
  String? _code;
  String? _msg;
  Map<String, dynamic>? results;
  List<dynamic>? resultList;

  BaseBeanEntry(
      this._code, this._msg, this.results, this.resultList); // BaseBeanEntry(
  //     {String? code,
  //     String? msg,
  //     Map<String, dynamic>? data,
  //     List<dynamic>? dataList}) {
  //   _code = code;
  //   _msg = msg;
  //   results = data;
  //   resultList = dataList;
  // }

  BaseBeanEntry.fromJson(dynamic json) {
    _code = json['code'];
    _msg = json['msg'];
    var dataJson = json['data'];
    if (dataJson is Map) {
      results = dataJson.cast<String, dynamic>();
    } else {
      resultList = dataJson;
    }
  }

  /// 获取单个对象
  T? getObj<T>() {
    if (results != null && results!.isNotEmpty) {
      //使用EntityFactory解析对象
      try {
        return EntryFactory.generateOBJ(results);
      } catch (e) {
        print(e);
      }
    }
    return null;
  }

  /// 获取集合
  List<T> getList<T>() {
    var list = <T>[];
    try {
      if (resultList != null) {
        resultList!.forEach((element) {
          //使用EntityFactory解析对象
          var generateOBJ = EntryFactory.generateOBJ<T>(element);
          list.add(generateOBJ!);
        });
      }
    } catch (e) {
      print(e);
    }
    return list;
  }
}
